<?php

require_once ('include/permiss.php');
require_once('config.php');
if ($_GET['action'] == 'del') {
    $order_id = $_GET['order_id'];
    $pdo = $conn->prepare('DELETE FROM datab_order WHERE order_id=?');
    $conn->beginTransaction();
    $pdo->execute(array($order_id));
    if ($pdo->rowCount()) {
        $pdo = $conn->prepare('DELETE FROM datab_order_product WHERE order_id=?');
        $kq = 0;
        $pdo->execute(array($order_id));
        if ($pdo->rowCount()) {
            $conn->commit();
            $kq = 1;
        } else {
            $conn->rollBack();
            $kq = 0;
        }
    }
    $redirect = 'order';
    if ($_GET['redirect'] == 'controlpanel') {
        $redirect = 'controlpanel';
    }
    header('Location: ' . $redirect . '.php?del=status&kq=' . $kq . "&token=" . $_GET['token']);
}

if (isset($_POST['submit'])) {
    if ($_POST['order_id'] && isset($_POST['products'])) {
        $pdo = $conn->prepare('DELETE FROM datab_order_product WHERE order_id=? AND  product_id IN(' . implode(',', $_POST['products']) . ')');
        $pdo->execute(array($_POST['order_id']));
        header('Location:controlpanel.php?token=' . $_SESSION['token']);
    }
}

if ($_GET['action'] == 'decrease') {
    $order_id = $_GET['order_id'];
    $product_id = $_GET['product_id'];

    $pdo = $conn->prepare('UPDATE datab_order_product SET order_quantity=order_quantity-1 WHERE order_id=? AND product_id=?');
    $pdo->execute(array($order_id, $product_id));
    if ($pdo->rowCount()) {
        $kq = 1;
    } else {
        $kq = 0;
    }

    header('Location: controlpanel.php?kq=' . $kq . "&token=" . $_GET['token']);

}

if ($_GET['action'] == 'increase') {
    $order_id = $_GET['order_id'];
    $product_id = $_GET['product_id'];

    $pdo = $conn->prepare('UPDATE datab_order_product SET order_quantity=order_quantity+1 WHERE order_id=? AND product_id=?');
    $pdo->execute(array($order_id, $product_id));
    if ($pdo->rowCount()) {
        $kq = 1;
    } else {
        $kq = 0;
    }

    header('Location: controlpanel.php?kq=' . $kq . "&token=" . $_GET['token']);

}

echo 'Không tồn tại thao tác này';
?>
